﻿Imports HslCommunication
Imports HslCommunication.Profinet.Siemens
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Public Class Form1
    Dim agv_website As String
    Dim objTaskTM As New clsTaskTM
    Dim objClsSysParam As New clsSysParam
    Dim objagvlog As New clsAgvLog
    Dim objtmj As New clsTmj
    Dim objtask As New clsTask
    Dim objProdInfo As New clsProdInfo
    '西门子1200对象
    Dim StripperPLC As SiemensS7Net
    'PLC是否连接成功
    Dim StripperPlcConFLG As Boolean = False

    Dim httphelper As New HttpHelper

    Dim ping = New Net.NetworkInformation.Ping()

    Dim dt As New DataTable

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Control.CheckForIllegalCrossThreadCalls = False
        If Not HslCommunication.Authorization.SetAuthorizationCode("98141214-0241-46e4-9dfe-a06f71c7edf4") Then

        End If
        If Not HslControls.Authorization.SetAuthorizationCode("ce5ade06-6f14-4b0d-b9c2-0d625664dc3f") Then

        End If
        connectDB()
        dt.Columns.Add("key")
        dt.Columns.Add("val")
        dt.Rows.Add("500", "1")
        dt.Rows.Add("600", "4")
        dt.Rows.Add("LRB700", "6")
        dt.Rows.Add("800", "8")
        dt.Rows.Add("900", "10")
        dt.Rows.Add("1000", "12")
        dt.Rows.Add("LNR700", "13")
        cmb_sm.DisplayMember = "key"
        cmb_sm.ValueMember = "val"
        cmb_sm.DataSource = dt
        cmbAgv.SelectedIndex = 0
        initAgvWebSite()
        StripperPLC = New SiemensS7Net(SiemensPLCS.S1200)
        StripperPLC.IpAddress = lblIp.Text
        StripperPLC.Port = 102
        StripperPLC.SetPersistentConnection()
        With UCtmjInfo1
            .StripperPLC_UC = StripperPLC
            .lan1 = lan1
            .lbl = lblStatus
            .tmPLC.Start()
        End With
        Try
            If UCtmjInfo1.StripperPlcConFLG_UC Then
                lblStatus.Text = "连接结果成功"
                HslLanternSimple1.LanternBackground = Color.LimeGreen
                HslLanternSimple2.LanternBackground = Color.Gray
                HslLanternSimple3.LanternBackground = Color.Gray
                HslLanternSimple4.LanternBackground = Color.Gray
            Else
                lblStatus.Text = "Ping失败！"
                lan1.LanternBackground = Color.Gray
            End If
        Catch ex As Exception
            lan1.LanternBackground = Color.Gray
            lblStatus.Text = "连接失败！"
            '连接失败
            'MsgBox("连接失败！")
        End Try
    End Sub

    Private Sub connectDB()

        g_szInitFileName = My.Application.Info.DirectoryPath & "\tmj_agv_deom.ini"

        g_Server.szDrive = GetIniFile("SERVER", "DRIVE", "PostgreSQL ANSI", g_szInitFileName)
        g_Server.szIPadr = GetIniFile("SERVER", "IP", "", g_szInitFileName)
        g_Server.szDbn = GetIniFile("SERVER", "DBN", "ZHENANSF", g_szInitFileName)
        g_Server.szUid = GetIniFile("SERVER", "UID", "sa", g_szInitFileName)
        g_Server.szPas = GetIniFile("SERVER", "PAS", "sa", g_szInitFileName)
        g_Server.iOver = CInt(GetIniFile("SERVER", "OVER", "-1", g_szInitFileName))

        If False = g_fDBconnect And 0 = g_iDBconnResult Then
            If "" = g_Server.szIPadr Or "0.0.0.0" = g_Server.szIPadr Then
            Else
                g_fDBconnect = True

                'データベース接続
                With g_Server
                    g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    If 1 <> g_iDBconnResult Then
                        .szDrive = CStr(IIf("PostgreSQL" = .szDrive, "PostgreSQL ANSI", "PostgreSQL"))
                        g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    End If
                End With
            End If
        End If

    End Sub

    Private Sub initAgvWebSite()
        Dim dt As DataTable = objClsSysParam.selectAgvWebSite()
        If dt.Rows.Count = 1 Then
            agv_website = dt.Rows(0)("param_value").ToString()
        End If
    End Sub
    Private Sub cmb_sm_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmb_sm.SelectedIndexChanged
        lblsmValue.Text = cmb_sm.SelectedValue.ToString()
    End Sub

    Private Function setTask(agv As String, oper As Integer) As String
        Dim msg As String
        If String.IsNullOrEmpty(agv_website) = False Then
            Dim url As String = agv_website & "AGVAPI?do=SetAGVState&agv=" & agv & "&oper=" & oper
            Try
                Dim rtn As String = httphelper.HttpGet(url, "")
                Dim jo As JObject = JsonConvert.DeserializeObject(rtn)
                Dim code As String = jo("code").ToString() '输出0
                msg = jo("msg").ToString() '输出ok
            Catch ex As Exception
                msg = "NG"
            End Try
        Else
            msg = "请联系工作人员，配置agv网址"
        End If
        Return msg
    End Function


    Private Function setAgvNewTask(id As String, prio As String, pick As String, drop As String, agv As String) As String
        Dim msg As String
        Dim interface_msg As String = String.Empty
        If String.IsNullOrEmpty(agv_website) = False Then
            Dim url As String = agv_website & "AGVAPI?do=NewTask&id=" & id & "&prio=" & prio & "&pick=" & pick & "&drop=" & drop & "&agv=" & agv
            Dim httphelper As HttpHelper = New HttpHelper()
            Dim rtn As String = String.Empty
            Try
                rtn = httphelper.HttpGet(url, "")
            Catch ex As Exception
                interface_msg = ex.Message
            End Try
            If String.IsNullOrEmpty(rtn) = False And String.IsNullOrEmpty(interface_msg) Then
                Dim jo As JObject = JsonConvert.DeserializeObject(rtn)
                Dim code As String = jo("code").ToString() '输出0
                msg = jo("msg").ToString() '输出ok
            Else
                msg = "调取agv接口失败，请确保开启AGV服务：" & interface_msg
            End If
        Else
            msg = "请联系工作人员，配置agv网址"
        End If
        Return msg
    End Function

    Private Sub btnArrvel1_Click(sender As Object, e As EventArgs) Handles btnArrvel1.Click
        If cmbAgv.Text = "" Then
            MsgBox("请选择AGV车号。")
            cmbAgv.Focus()
            Exit Sub
        End If
        Dim rtn11 As String = readStripperPlc("DB47.DBX0.0")
        If rtn11 = False.ToString() Then
            If MsgBox("确认要进行此操作吗？", vbYesNo, "提示") = vbYes Then
                Dim b2 As Boolean = writeStripperBytePlc("DB47.DBX10", Byte.Parse(cmb_sm.SelectedValue.ToString())) 'AGV车上支座型号写入
                Threading.Thread.Sleep(2000)
                Dim b1 As Boolean = writeStripperBoolPlc("DB47.DBX11.0", True) 'AGV车到位写入
                If b2 And b1 Then
                    MsgBox("AGV车上支座型号写入：成功；AGV车到位写入：成功")
                ElseIf b2 Then
                    MsgBox("AGV车上支座型号写入：成功")
                ElseIf b1 Then
                    MsgBox("AGV车到位写入：成功")
                Else
                    MsgBox("AGV车上支座型号写入：失败；AGV车到位写入： 失败")
                End If
                If b1 And b2 Then
                    HslLanternSimple1.LanternBackground = Color.Gray
                    HslLanternSimple2.LanternBackground = Color.LimeGreen
                    HslLanternSimple3.LanternBackground = Color.Gray
                    HslLanternSimple4.LanternBackground = Color.Gray
                End If
            End If
        Else
            MsgBox("脱模机状态忙")
        End If
    End Sub

    Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
        If cmbAgv.Text = "" Then
            MsgBox("请选择AGV车号。")
            cmbAgv.Focus()
            Exit Sub
        End If

        'If Label8.Text.Equals("支座拿取结果：True") Then
        If MsgBox("确认要进行此操作吗？", vbYesNo, "提示") = vbYes Then
            Dim rtnmsg As String = setTask(cmbAgv.Text, 1)
            If rtnmsg.Equals("ok") Then
                HslLanternSimple1.LanternBackground = Color.Gray
                HslLanternSimple2.LanternBackground = Color.Gray
                HslLanternSimple3.LanternBackground = Color.LimeGreen
                HslLanternSimple4.LanternBackground = Color.Gray
                MsgBox("执行AGV启成功")
                Dim bx As Boolean = writeStripperBoolPlc("DB47.DBX11.0", False)
                If bx Then
                    MsgBox("AGV车到位更新写入：成功")
                Else
                    MsgBox("AGV车到位更新写入：失败")
                End If
            Else
                MsgBox("执行AGV启失败")
            End If

        End If
        'Else
        '    MsgBox("支座拿取结果，请确认")
        'End If
    End Sub

    Private Sub btnArrvel2_Click(sender As Object, e As EventArgs) Handles btnArrvel2.Click
        If cmbAgv.Text = "" Then
            MsgBox("请选择AGV车号。")
            cmbAgv.Focus()
            Exit Sub
        End If
        If MsgBox("确认要进行此操作吗？", vbYesNo, "提示") = vbYes Then
            Dim b3 As Boolean = writeStripperBoolPlc("DB47.DBX11.3", True) 'AGV移动到位写入
            If b3 Then
                MsgBox("AGV移动到位写入：成功")
                HslLanternSimple1.LanternBackground = Color.Gray
                HslLanternSimple2.LanternBackground = Color.Gray
                HslLanternSimple3.LanternBackground = Color.Gray
                HslLanternSimple4.LanternBackground = Color.LimeGreen
            Else
                MsgBox("AGV移动到位写入：失败")
            End If
        End If
    End Sub

    Private Sub btnStart1_Click(sender As Object, e As EventArgs) Handles btnStart1.Click
        If cmbAgv.Text = "" Then
            MsgBox("请选择AGV车号。")
            cmbAgv.Focus()
            Exit Sub
        End If
        'If Label9.Text.Equals("芯座拿取结果：True") Then\
        If MsgBox("确认要进行此操作吗？", vbYesNo, "提示") = vbYes Then
            Dim b1 As Boolean = writeStripperBoolPlc("DB47.DBX11.1", True)
            Dim rtnxyz As String = readStripperPlc("DB47.DBX0.5")
            If rtnxyz = True.ToString() Then
                Dim rtn113 As Boolean = writeStripperBoolPlc("DB47.DBX11.3", False)
                Dim rtnxzc As String = readStripperPlc("DB47.DBX11.3")
                If rtnxzc = False.ToString() Then
                    For index = 0 To 3
                        writeStripperBoolPlc("DB47.DBX11.3", False)
                    Next
                End If
                writeStripperBoolPlc("DB47.DBX11.0", False)
                writeStripperBytePlc("DB47.DBX10", Byte.Parse(0)) 'AGV车上支座型号重新标记为0
                HslLanternSimple1.LanternBackground = Color.LimeGreen
                HslLanternSimple2.LanternBackground = Color.Gray
                HslLanternSimple3.LanternBackground = Color.Gray
                HslLanternSimple4.LanternBackground = Color.Gray
                MsgBox("AGV送货结果写入：成功")
                'Dim rtnmsg As String = setTask(cmbAgv.Text, 1)
                Dim rtnmsg As String = setAgvNewTask(Now.ToString(), "0", "112", "113", cmbAgv.Text)
                If rtnmsg.Equals("ok") Then
                    MsgBox("执行AGV启成功")
                    cmbAgv.Text = ""
                Else
                    MsgBox("执行AGV启失败")
                End If
                'Threading.Thread.Sleep(3000)
                writeStripperBoolPlc("DB47.DBX11.1", False)

                UCtmjInfo1.reset_last_flg = True
                UCtmjInfo1.reset_start_time = Now()
                'System.Threading.Thread.Sleep(12000)

            Else
                MsgBox("AGV送货结果写入：失败")
            End If
        End If

        'Else
        '    MsgBox("芯座拿取结果，请确认")
        'End If
    End Sub

    Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click

        If cmbAgv.Text = "" Then
            MsgBox("请选择AGV车号。")
            cmbAgv.Focus()
            Exit Sub
        End If
        If MsgBox("确认要进行此操作吗？", vbYesNo, "提示") = vbYes Then
            Dim rtnmsg As String = setTask(cmbAgv.Text, 0)
            If rtnmsg.Equals("ok") Then
                MsgBox("执行AGV停成功", MsgBoxStyle.Information)
            Else
                MsgBox("执行AGV停失败", MsgBoxStyle.Critical)
            End If

        End If
    End Sub

    Private Function readStripperPlc(place As String) As String
        '执行plc读取操作
        If UCtmjInfo1.StripperPlcConFLG_UC Then
            Return readStripper(place, StripperPLC)
        Else
            Return String.Empty
        End If
    End Function

    Private Function readStripper(place As String, plc As SiemensS7Net) As String
        '	RGV当前状态	Int	2.0
        Dim status As String = plc.ReadBool(place).Content
        Return status
    End Function
    Private Function readStripperByte(place As String, plc As SiemensS7Net) As String
        '	RGV当前状态	Int	2.0
        Dim status As String = plc.ReadByte(place).Content
        Return status
    End Function

    Private Function writeStripperBoolPlc(place As String, val As Boolean) As Boolean
        If UCtmjInfo1.StripperPlcConFLG_UC Then
            Return WriteStripperBool(place, val, StripperPLC)
        Else
            Return False
        End If
    End Function
    Private Function writeStripperBytePlc(place As String, val As Byte) As Boolean
        If UCtmjInfo1.StripperPlcConFLG_UC Then
            Return writeStripperByte(place, val, StripperPLC)
        Else
            Return False
        End If
    End Function
    Private Function WriteStripperBool(place As String, val As Boolean, plc As SiemensS7Net) As Boolean
        '查询脱模机状态等条件
        'Dim dt As DataTable = objStripper.getList(strippername)
        'If dt.Rows(0)("status").ToString().Equals("1") Then
        '    '如果满足条件 则进行更新
        'End If
        Dim OperR As OperateResult = plc.Write(place, val)
        Return OperR.IsSuccess
    End Function

    Private Function writeStripperByte(place As String, val As Byte, plc As SiemensS7Net) As Boolean
        '查询脱模机状态等条件
        'Dim dt As DataTable = objStripper.getList(strippername)
        'If dt.Rows(0)("status").ToString().Equals("1") Then
        '    '如果满足条件 则进行更新
        'End If
        Dim OperR As OperateResult = plc.Write(place, val)
        Return OperR.IsSuccess
    End Function

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        If UCtmjInfo1.StripperPlcConFLG_UC Then
            StripperPLC.ConnectClose()
            UCtmjInfo1.tmPLC.Stop()
        End If
    End Sub

    Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
        DBacs.Disconnect()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim b1 As Boolean = writeStripperBoolPlc("DB47.DBX11.0", False) 'AGV车到位写入
        Dim b2 As Boolean = writeStripperBytePlc("DB47.DBX10", Byte.Parse(0)) 'AGV车上支座型号写入
    End Sub

    Private Sub cmbAgv_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbAgv.SelectedIndexChanged
        UCtmjInfo1.agv = cmbAgv.Text
    End Sub

    Private Sub btnStart0_Click(sender As Object, e As EventArgs) Handles btnStart0.Click
        '查询最新的一条脱模记录
        'Dim dt As DataTable = objtmj.selectTmj()
        'Dim dt As DataTable = objClsSysParam.selectAgvTmj()
        'Label3.Text = "AGV:" & dt.Rows(0)("param_value").ToString()
        If MsgBox("确认要启动该AGV吗？", vbYesNo, "提示") = vbYes Then

            Dim dt As DataTable = objTaskTM.SelectTaskTMByStatus("任务完成")
            If dt.Rows.Count > 0 Then
                Label3.Text = "AGV:" & dt.Rows(0)("agv").ToString()
                Dim b1 As Boolean = writeStripperBoolPlc("DB47.DBX11.1", True)
                Dim rtnxyz As String = readStripperPlc("DB47.DBX0.5")
                If rtnxyz = True.ToString() Then
                    Dim rtn113 As Boolean = writeStripperBoolPlc("DB47.DBX11.3", False)
                    Dim rtnxzc As String = readStripperPlc("DB47.DBX11.3")
                    If rtnxzc = False.ToString() Then
                        For index = 0 To 3
                            writeStripperBoolPlc("DB47.DBX11.3", False)
                        Next
                    End If
                    writeStripperBoolPlc("DB47.DBX11.0", False)
                    writeStripperBytePlc("DB47.DBX10", Byte.Parse(0)) 'AGV车上支座型号重新标记为0
                    Dim localip As String = GetIPAddr()
                    objagvlog.add(localip, dt.Rows(0)("agv").ToString(), "启动", "脱模机下agv启动")
                    Dim rtnms1g As Integer = objtmj.update_agv_start2(1, dt.Rows(0)("task_id").ToString())
                    If rtnms1g <> -2 Then
                        If dt.Rows(0)("task_id").ToString().Equals("0") = False Then
                            objTaskTM.updateTaskTMStatusByTaskId("任务完成启动", dt.Rows(0)("task_id").ToString())
                            objProdInfo.updateTM(dt.Rows(0)("prod_id").ToString(), "脱模机")
                            'objtask.task_transfer(dt.Rows(0)("prod_id").ToString())
                            'Dim rtnmsg As String = setTask(dt.Rows(0)("agv").ToString(), 1)
                            writeStripperBoolPlc("DB47.DBX11.1", False)
                            Dim rtnmsg As String
                            rtnmsg = setAgvNewTask(Now.ToString(), "0", "112", "113", dt.Rows(0)("agv").ToString())
                            If rtnmsg.Equals("ok") Then
                                'objClsSysParam.update_agv_tmj("0", "0")
                                MsgBox("启动成功")
                                Close()
                            Else
                                MsgBox("AGV启动错误信息：" & rtnmsg)
                                rtnmsg = setAgvNewTask(Now.ToString(), "0", "112", "113", dt.Rows(0)("agv").ToString())
                                If rtnmsg.Equals("ok") Then
                                    MsgBox("启动成功")
                                    Close()
                                Else
                                    MsgBox("AGV启动错误信息：" & rtnmsg)
                                    rtnmsg = setAgvNewTask(Now.ToString(), "0", "112", "113", dt.Rows(0)("agv").ToString())
                                    If rtnmsg.Equals("ok") Then
                                        MsgBox("启动成功")
                                        Close()
                                    Else
                                        MsgBox("AGV启动错误信息：" & rtnmsg & "，请联系管理员进行处理！")
                                    End If
                                End If
                            End If
                        End If
                    Else
                        MsgBox("启动脱模机数据失败")
                    End If
                Else
                    MsgBox("AGV送货结果写入：失败")
                End If
            Else
                MsgBox("未检索到脱模机下可以启动的AGV")
            End If
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim b1 As Boolean = writeStripperBoolPlc("DB47.DBX11.1", True)
        Dim rtnxyz As String = readStripperPlc("DB47.DBX0.5")
        If rtnxyz = True.ToString() Then
            Dim rtn113 As Boolean = writeStripperBoolPlc("DB47.DBX11.3", False)
            Dim rtnxzc As String = readStripperPlc("DB47.DBX11.3")
            If rtnxzc = False.ToString() Then
                For index = 0 To 3
                    writeStripperBoolPlc("DB47.DBX11.3", False)
                Next
            End If
            writeStripperBoolPlc("DB47.DBX11.0", False)
            writeStripperBytePlc("DB47.DBX10", Byte.Parse(0)) 'AGV车上支座型号重新标记为0
        End If
    End Sub
End Class